<template>
  <div>
    <el-form @submit.native.prevent :inline="true" :model="params">
      <el-form-item>
        <!-- <select-org-bank v-model="bankId"
                         placeholder="选择银行"
                         filterable
                         clearable
                         @select="selectBank"></select-org-bank> -->
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="selectDate"
          @change="setParams"
          type="month"
          placeholder="选择月"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
        <el-button icon="el-icon-download" :loading="exportLoading" @click="exportToExcel()">
          下载
        </el-button>
      </el-form-item>
    </el-form>
    <div class="w-100">
      <el-echarts theme="macarons" :height="320" :loading="loading" :option="option"></el-echarts>
    </div>
    <div :id="exportId">
      <table class="table table-bordered table-sm table-vertical-middle" v-loading="loading">
        <colgroup>
          <col width="5%" />
          <col width="9%" />
          <col width="9%" />
          <col width="9%" />
          <col width="9%" />
          <col width="9%" />
          <col width="9%" />
          <col width="9%" />
          <col width="8%" />
          <col width="8%" />
          <col width="8%" />
          <col width="8%" />
        </colgroup>
        <thead class="text-center bg-light">
          <tr>
            <td rowspan="2">序号</td>
            <td rowspan="2">地区</td>
            <td rowspan="2">银行机构</td>
            <td rowspan="2">年初在保余额</td>
            <td rowspan="2">新增在保金额</td>
            <td rowspan="2">解保金额</td>
            <td rowspan="2">在保金额</td>
            <td colspan="3">60天内即将到期</td>
            <td rowspan="2">办理机构</td>
            <td rowspan="2">备注</td>
          </tr>
          <tr>
            <td>即将解保数</td>
            <td>解保后的在保余额</td>
            <td>与年初数比较 (±)</td>
          </tr>
        </thead>
        <tbody>
          <tr v-if="!tableData.length">
            <td colspan="12" style="height: 120px" class="text-center">暂无数据</td>
          </tr>
          <tr v-for="(item, index) in tableData" :key="index">
            <td class="text-center">{{ index + 1 }}</td>
            <td class="text-center" v-if="item.rowspan" :rowspan="item.rowspan">
              {{ item.address }}
            </td>
            <td class="text-center">{{ item.bank_name }}</td>
            <td class="text-center">{{ item.year_begin_on_funds }}</td>
            <td class="text-center">{{ item.new_on_funds }}</td>
            <td class="text-center">{{ item.un_funds }}</td>
            <td class="text-center">{{ item.on_funds }}</td>
            <td class="text-center">{{ item.will_un_total }}</td>
            <td class="text-center">{{ item.will_un_beh_funds }}</td>
            <td class="text-center">{{ item.contrast }}</td>
            <td class="text-center">{{ item.service_name }}</td>
            <td class="text-left">{{ item.remark }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import { add, sub, excelTableExport, echartsXFormatter } from '@vimi/utils-tool'

import { calcSpan } from '@/common/plugins/tools/common'

// import SelectOrgBank from '@/bigcredit/views/program/components/SelectOrgBank'
function getStyle(params) {
  const unit = params.seriesName.includes('占比') ? '%' : '万元'
  return `<div style="width: 10px; height: 10px; background-color:${params.color}; border-radius: 10px; display: inline-block; line-height: 10px;"></div>  
            ${params.seriesName}：${params.data} ${unit} <br />`
}

const addressGroup = {
  1: '业务一组 (贵阳、毕节、遵义地区)',
  2: '业务二组 (黔东南、黔南地区)',
  3: '业务三组 (黔西南、六盘水、安顺地区)',
  4: '业务四组 (铜仁地区)',
}
export default {
  components: {
    // SelectOrgBank
  },
  props: {},
  data() {
    return {
      loading: false,
      params: {
        isBIQuery: 1,
      },
      order: {
        group_type: 'asc',
      },
      tableData: [],
      option: {},
      tableName: 'report_analysis_manage_view',
      selectDate: new Date(),
      bankId: '',
      exportLoading: false,
    }
  },
  computed: {
    fileName() {
      return '“黔农十二贷”统计表'
    },
    exportId() {
      return 'table-print'
    },
  },
  watch: {},
  created() {
    this.params['current_month.eq'] = this.$utils.dateFormat(this.selectDate, 'yyyyMM')
    this.getData()
  },
  mounted() {},
  methods: {
    async exportToExcel() {
      this.exportLoading = true
      excelTableExport(this.exportId, this.fileName, {
        styles: {
          // 全局样式
          border: {
            left: { style: 'thin' },
            top: { style: 'thin' },
            right: { style: 'thin' },
            bottom: { style: 'thin' },
          },
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        // 单元格样式，最顶级设置(styles -> dataset -> cellStyles)
        // 可以设置成 A1，或 'r-c' 的主键
        cellStyles: {},
      })
        .catch(err => {
          const msg = (err && err.message) || ''
          this.$message.error(`导出失败，请重试！${msg}`)
        })
        .finally(() => {
          this.exportLoading = false
        })
    },
    selectBank(bank) {
      this.params.bank_name = bank.agency_name || ''
      this.getData()
    },
    setParams() {
      this.selectDate = this.selectDate ? this.selectDate : new Date()
      this.params['current_month.eq'] = this.$utils.dateFormat(this.selectDate, 'yyyyMM')
      this.getData()
    },
    getData() {
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          const data = calcSpan((res && res.data) || [], 'group_type')
          this.tableData = data.map(this.dataAdapter)
          this.getOption(this.tableData)
        })
        .finally(() => {
          this.loading = false
        })
    },
    dataAdapter(item, index) {
      item.new_on_funds = item.new_on_funds || 0
      item.on_funds = item.on_funds || 0
      item.un_funds = item.un_funds || 0
      item.index = index + 1
      item.contrast = sub(item.will_un_beh_funds, item.year_begin_on_funds)
      item.address = `${addressGroup[item.group_type]} (${item.group_name})`
      return item
    },
    getOption(data) {
      const newOnFunds = []
      const onFunds = []
      const unFunds = []
      let newOnFundsTotal = 0
      let onFundsTotal = 0
      let unFundsTotal = 0
      const dataObject = {}
      data.forEach(item => {
        if (dataObject[item.group_type]) {
          dataObject[item.group_type].newOnFunds = add(
            dataObject[item.group_type].newOnFunds,
            item.new_on_funds
          )
          dataObject[item.group_type].onFunds = add(
            dataObject[item.group_type].onFunds,
            item.on_funds
          )
          dataObject[item.group_type].unFunds = add(
            dataObject[item.group_type].unFunds,
            item.un_funds
          )
        } else {
          dataObject[item.group_type] = {
            newOnFunds: item.new_on_funds,
            onFunds: item.on_funds,
            unFunds: item.un_funds,
          }
        }
        newOnFundsTotal = add(newOnFundsTotal, item.new_on_funds)
        onFundsTotal = add(onFundsTotal, item.on_funds)
        unFundsTotal = add(unFundsTotal, item.un_funds)
      })
      const newOnFundsRate = []
      const onFundsRate = []
      const unFundsRate = []
      Object.keys(addressGroup).forEach(key => {
        const item = dataObject[key] || {}
        newOnFunds.push(item.newOnFunds || 0)
        onFunds.push(item.onFunds || 0)
        unFunds.push(item.unFunds || 0)
        newOnFundsRate.push(
          Math.round(((item.newOnFunds || 0) / (newOnFundsTotal || 1)) * 10000) / 100
        )
        onFundsRate.push(Math.round(((item.onFunds || 0) / (onFundsTotal || 1)) * 10000) / 100)
        unFundsRate.push(Math.round(((item.unFunds || 0) / (unFundsTotal || 1)) * 10000) / 100)
      })

      this.setOption({ newOnFunds, onFunds, unFunds, newOnFundsRate, onFundsRate, unFundsRate })
    },
    setOption(data) {
      const xData = []
      Object.keys(addressGroup).forEach(key => {
        xData.push(addressGroup[key])
      })
      this.option = {
        title: [
          {
            text: '小组片区',
            subtext: data.subtext,
          },
        ],
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            return params.reduce((a, b, index) => {
              return a + getStyle(params[index])
            }, '')
          },
          backgroundColor: 'rgba(50,50,50,0.7)',
        },
        legend: {
          type: 'scroll',
          padding: [30, 200],
          data: [
            '新增在保金额',
            '在保金额',
            '解保金额',
            '新增在保金额占比',
            '在保金额占比',
            '解保金额占比',
          ],
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        grid: {
          top: 80,
          left: 50,
          right: 50,
        },
        xAxis: [
          {
            type: 'category',
            data: xData,
            axisLabel: {
              formatter: v => echartsXFormatter(v, 8),
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '金额(万元)',
          },
          {
            type: 'value',
            name: '金额占比(%)',
          },
        ],
        series: [
          {
            name: '新增在保金额',
            type: 'bar',
            barMaxWidth: 60,
            data: data.newOnFunds,
            label: { show: true, position: 'top', formatter: '{c}万元' },
          },
          {
            name: '在保金额',
            type: 'bar',
            data: data.onFunds,
            label: { show: true, position: 'top', formatter: '{c}万元' },
          },
          {
            name: '解保金额',
            type: 'bar',
            data: data.unFunds,
            label: { show: true, position: 'top', formatter: '{c}万元' },
          },
          {
            name: '新增在保金额占比',
            type: 'line',
            data: data.newOnFundsRate,
            yAxisIndex: 1,
            label: { show: true, position: 'right', formatter: '{c}%' },
          },
          {
            name: '在保金额占比',
            type: 'line',
            data: data.onFundsRate,
            yAxisIndex: 1,
            label: { show: true, position: 'right', formatter: '{c}%' },
          },
          {
            name: '解保金额占比',
            type: 'line',
            data: data.unFundsRate,
            yAxisIndex: 1,
            label: { show: true, position: 'right', formatter: '{c}%' },
          },
        ],
      }
    },
  },
}
</script>

<style lang="scss" scoped></style>
